import kivy
kivy.require('1.0.6')

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.slider import Slider
from kivy.uix.widget import Widget
from kivy.uix.scatter import Scatter
from kivy.uix.textinput import TextInput
from kivy.uix.treeview import TreeView, TreeViewLabel
from kivy.uix.switch import Switch
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty
from kivy.clock import Clock
from kivy.uix.video import Video
from kivy.uix.image import AsyncImage
import time

from weather import get_weather
import feedparser

from threading import Thread, Event, Timer
import time

class ControlButton(Button):
    def __init__(self, *args, **kwargs):
      Button.__init__(self, *args, **kwargs)
      self.sc = kwargs['sc']
    def on_press(self):
      self.sc.content.clear_widgets()
      try:
        if self.text in PANEL_CACHE:
          w = PANEL_CACHE[self.text]
        else:
          w = globals()[self.text]()
        self.sc.content.add_widget(w)
      except Exception as e:
        print e, e.message

class TouchUI(FloatLayout):
    notification = ObjectProperty(None)
    clock = ObjectProperty(None)
    buttons = ObjectProperty(None)
    content = ObjectProperty(None)

class NewsItem(BoxLayout):
    title = ObjectProperty(None)
    summary = ObjectProperty(None)
    icon = ObjectProperty(None)
    def __init__(self, *args, **kwargs):
      BoxLayout.__init__(self, *args, **kwargs)
      #self.bind(on_touch_down=self.on_press)
    def callback(self, instance):
      if self.video:
        self.video.play = False
    def on_press(self, instance, event):
      content = BoxLayout(orientation='vertical')
      self.video = Video(source='225432923ONL1108266308486.urlFLVLong.flv', play=True)
      content.add_widget(self.video)

      popup = Popup(content=content, title='More',
                    size_hint=(0.8, 0.8))
      popup.bind(on_dismiss=self.callback)
      popup.open()
      
    
class NewsEntry(Button):
    def __init__(self, *args, **kwargs):
      Button.__init__(self, *args, **kwargs)
      entry = kwargs['entry']
      self.summary = entry.summary
      self.icon = entry.icon
      #if self.child.icon.endswith('.flv'):
      #self.item.icon.add_widget(Video(source=self.child.icon))
      self.icon_widget = AsyncImage(source=self.icon)
      print 'ICON', self.icon
    def on_press(self):
      print 'NewsEntry', self.parent.parent.parent
      self.parent.parent.parent.make_active(self)

class Section(BoxLayout):
    header = ObjectProperty(None)
    temperature = ObjectProperty(None)
    feels = ObjectProperty(None)
    icon = ObjectProperty(None)
    description = ObjectProperty(None)
    pass

PANEL_CACHE = {}

class Main(BoxLayout):
    def __init__(self, *args, **kwargs):
        BoxLayout.__init__(self, *args, **kwargs)
        PANEL_CACHE['Main'] = self
        self.current_child = 0
        self.item = NewsItem()
        self.newscontent.add_widget(self.item)
        self.child = None
        Clock.schedule_interval(self.callbacker, 50)
        
    def make_active(self, child):
        if self.child: self.child.state = 'normal'
        self.child = child
        self.item.title.text = self.child.text
        self.item.summary.text = self.child.summary
        self.item.icon.clear_widgets()
        self.item.icon.add_widget(self.child.icon_widget)
        self.child.state = 'down'
          
    def callbacker(self, dt):
        nr = len(self.news.children)
        if nr:
          if self.current_child >= nr:
            self.current_child = 0
          child = self.news.children[self.current_child]
          self.make_active(child)
          self.current_child+=1

class LightsSection(BoxLayout):
  name = ObjectProperty(None)
  grid = ObjectProperty(None)
  
class Light(BoxLayout):
  name = ObjectProperty(None)
  icon = ObjectProperty(None)

  
class Lights(BoxLayout):
  globals = ObjectProperty(None)
  groups = ObjectProperty(None)
  individuals = ObjectProperty(None)
  def __init__(self, *args, **kwargs):
    BoxLayout.__init__(self, *args, **kwargs)
    PANEL_CACHE['Lights'] = self
    for light in ['All off', 'All on']:
      l = Light()
      l.name.text = light
      self.globals.grid.add_widget(l)
    for light in ['Downstairs', 'Upstairs', 'Outside', 'Bedrooms']:
      l = Light()
      l.name.text = light
      self.groups.grid.add_widget(l)
    for light in ['Kitchen', 'Living', 'Hall', 'Study', 'Garage']:
      l = Light()
      l.name.text = light
      self.individuals.grid.add_widget(l)
 

class NotificationArea(BoxLayout):
  notifications = ObjectProperty(None)
  clock = ObjectProperty(None)
  def __init__(self, *args, **kwargs):
    BoxLayout.__init__(self, *args, **kwargs)
    self.lines = []
      
  def Text(self, msg):
    self.lines.insert(0, msg)
    self.lines = self.lines[:5]
    print 'ARR', '\n'.join(self.lines)
    self.notifications.text = '\n'.join(self.lines)


class TouchUIApp(App):
    def callbacker(self, dt):
        time.tzset()
        self.sc.clock.text = time.strftime('%H:%M')
        
    def build(self):
        sc = TouchUI()

        sc.buttons.add_widget(ControlButton(text='Main', sc=sc))
        sc.buttons.add_widget(ControlButton(text='Thermo', sc=sc))
        sc.buttons.add_widget(ControlButton(text='Lights', sc=sc))
        sc.buttons.add_widget(ControlButton(text='Settings', sc=sc))
        
        main = Main()
        lights = Lights()
        sc.content.add_widget(main)
        #sc.content.add_widget(lights)
        self.sc = sc
        
        self.callbacker(0)
        Clock.schedule_interval(self.callbacker, 10)
        
        self.weather_service = WeatherService(main)
        self.news_service = NewsService(main)
        
        app.location_service.init(sc)
        
        time.tzset()
        sc.notification.Text('Startup at %s'%(time.strftime('%a, %d %b %Y %H:%M:%S +0000')))
        sc.notification.Text('sueastside has entered the house.')
        sc.notification.Text('sueastside has left the house.')
        sc.notification.Text('New e-mail for sueastside@gmail.com')
        
        return sc
        
    def __del__(self):
      print 'TouchUIApp des'
      self.weather_service.exit()
      self.weather_service.join()
      self.news_service.exit()
      self.news_service.join()



from service import IntervalService, EventService

class WeatherService(IntervalService):
  def __init__(self, main):
    IntervalService.__init__(self, self.on_success, timeout=50)
    self.main = main
  def do(self):
    return get_weather()
  def on_success(self, service, forecasts):
    self.main.weather.clear_widgets()
    for i, forecast in enumerate(forecasts):
      if i == 0:
        s = Section(size_hint_x=1.7)
        s.feels.text = 'Feels like\n'+forecast.feels_like
        s.temperature.font_size=50
      else:
        s = Section()
      s.header.text = forecast.name
      s.temperature.text = forecast.temperature
      s.description.text = forecast.description
      s.icon.source = forecast.icon
      self.main.weather.add_widget(s)  


class NewsService(IntervalService):
  def __init__(self, main):
    IntervalService.__init__(self, self.on_success, timeout=50)
    self.main = main
  def do(self):
    class Entry:
      def __init__(self, entry):
        self.title = entry.title
        self.summary = getattr(entry, 'summary', '')
        self.icon = 'border.png'
        for link in entry.links:
          if link.rel == 'enclosure' and not link.href.endswith('.flv'):
            self.icon = link.href
            break
    entries = []
    d = feedparser.parse("http://www.deredactie.be/cm/vrtnieuws?mode=atom")
    for e in d['entries'][:6]:
      entries.append(Entry(e))
    return entries
  def on_success(self, service, entries):
    self.main.news.clear_widgets()
    for entry in entries:
      self.main.news.add_widget(NewsEntry(text=entry.title, font_size=15, entry=entry))     
    self.main.callbacker(0)


class LocationService(EventService):
  def __init__(self):
    EventService.__init__(self, "^house\\.location.*$")

  def init(self, sc):
    self.sc = sc
    self.start()
  
  def on_event(self,event):
    if event.subject == 'house.location.entered':
      msg = event.msg +' has entered.'
    elif event.subject == 'house.location.exited':
      msg = event.msg +' has left.'
    elif event.subject == 'house.location.entered.unknow':
      msg = 'unknown device detected' + str(event.msg)
    elif event.subject == 'house.location.ping':
      msg = 'ping, ' + str(event.msg)
    self.sc.notification.Text(msg)


    
          
if __name__ in ('__main__', '__android__'):
    from kivy.factory import Factory
    Factory.register('NotificationArea', module='main')
    Factory.register('LightsSection', module='main')

    app = TouchUIApp()
    app.location_service = LocationService()
    TouchUIApp().run()
